package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.Result;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.pojo.Category;
import com.itheima.reggie.pojo.Dish;
import com.itheima.reggie.pojo.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author gakki
 * @create 2022/5/2 17:19
 */
@Slf4j
@RestController
 @RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 菜品管理分页查询
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public Result<Page> queryByPage(Integer page, Integer pageSize, String name) {
        log.info("菜品管理分页查询page：{},pageSize:{},name:{}", page, pageSize,name);

        //创建两歌类型的Page分页查询，用于后面的拷贝
        Page<Dish> dishPage = new Page<>(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>();
        //sql语句执行，Dish类型的Page数据
        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.apply(name != null, "name REGEXP {0}", name).orderByDesc(Dish::getUpdateTime);
        dishService.page(dishPage, lambdaQueryWrapper);

        //拷贝page,排除record
        BeanUtils.copyProperties(dishPage, dishDtoPage, "records");

        //获取dish中的records
        List<Dish> dishList = dishPage.getRecords();

        //遍历records集合，将categoryId替换成categoryName
        List<DishDto> dishDtoList = dishList.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            Category category = categoryService.getById(item.getCategoryId());
            if (category != null) {
                dishDto.setCategoryName(category.getName());
            }
            return dishDto;
        }).collect(Collectors.toList());

        //将dishDtoPage中的records设置为上面的list
        dishDtoPage.setRecords(dishDtoList);

        return Result.success(dishDtoPage);
    }

    /**
     * 菜品及口味保存
     *
     * @param dishDto
     * @return
     */
    @PostMapping
    public Result<String> saveWithFlavor(@RequestBody DishDto dishDto) {
        log.info("保存添加的菜品dishDto：{}", dishDto);
        dishService.saveWithFlavor(dishDto);

        //删除该分类下的菜品缓存数据
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);

        return Result.success("菜品保存成功！");
    }

    /**
     * 根据菜品id查询菜品及口味信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result<DishDto> queryByDishId(@PathVariable Long id) {
        log.info("根据id查询菜品及口味：{}", id);
        DishDto dishDto = dishService.queryByDishId(id);
        return Result.success(dishDto);
    }

    /**
     * 更新菜品及口味
     *
     * @param dishDto
     * @return
     */
    @PutMapping
    public Result<String> updateWithFlavor(@RequestBody DishDto dishDto) {
        log.info("更新菜品及口味dishDto:{}", dishDto);
        dishService.updateWithFlavor(dishDto);
        //删除该菜品下的缓存
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);
        return Result.success("修改菜品成功！");
    }

    /**
     * 菜品删除及批量删除
     * @param ids
     * @return
     */
    @DeleteMapping
    public Result<String> deleteByIds(@RequestParam("ids") List<Long> ids) {
        log.info("删除及批量删除ids：{}", ids);
        //删除dish
        dishService.removeByIds(ids);
        //删除dish_flavor
        for (Long id : ids) {
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper();
            lambdaQueryWrapper.eq(DishFlavor::getDishId, id);
            dishFlavorService.remove(lambdaQueryWrapper);
        }
        return Result.success("删除成功！");
    }

    /**
     * 单个或批量更新菜品状态
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public Result<String> enableOrDisableDishStatus(@PathVariable Integer status,@RequestParam("ids") List<Long> ids) {
        log.info("单个或批量更新菜品状态！ids：{}",ids);
        for (Long id : ids) {
            LambdaUpdateWrapper<Dish> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            lambdaUpdateWrapper.set(Dish::getStatus, status).eq(Dish::getId, id);
            dishService.update(lambdaUpdateWrapper);
        }
        return Result.success("状态更新成功！");
    }


    /**
     * 菜品及口味展示
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public Result<List<DishDto>> dishList(Dish dish) {
        log.info("菜品根据category展示，categoryId：{}", dish.getCategoryId());
        //设置key
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();
        //判断缓存中是否存在数据
        ValueOperations valueOperations = redisTemplate.opsForValue();
        List<DishDto> dishDtos = (List<DishDto>) valueOperations.get(key);

        //如果缓存中有数据，则直接返回
        if (dishDtos != null) {
            return Result.success(dishDtos);
        } else {
            //如果缓存中没有数据，则从MySQL中加载
            //根据数据查询dish信息
            LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
            lambdaQueryWrapper.eq(Dish::getStatus, 1).orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
            List<Dish> dishList = dishService.list(lambdaQueryWrapper);

            //根据dish中的id，去dishflavor表中查询对应数据并封装
            List<DishDto> dishDtoList = dishList.stream().map((item)->{
                DishDto dishDto = new DishDto();
                BeanUtils.copyProperties(item, dishDto);
                LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
                dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId, item.getId());
                List<DishFlavor> dishFlavorList = dishFlavorService.list(dishFlavorLambdaQueryWrapper);
                dishDto.setFlavors(dishFlavorList);
                return dishDto;
            }).collect(Collectors.toList());
            //如果加载的数据不为null，则写入缓存并返回
            if (dishDtoList != null) {
                valueOperations.set(key, dishList);
            }
            //如果加载的数据为null，则直接返回
            return Result.success(dishDtoList);
        }
    }
}
